package showtime.framework.ui
{
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;

	public class PrinterTextField extends UIComponent
	{		
		private var _handle:Function = null;
		
		private var _timer:Timer = null;
		
		protected var _textField:TextField = null;
		
		protected var _delay:int = 0;
		
		protected var _text:String = null;
		
		public function PrinterTextField(delay:int, handle:Function = null, parent:DisplayObjectContainer = null, xpos:Number = 0, ypos:Number = 0)
		{
			_delay = delay;
			_handle = handle;
			
			super(parent, xpos, ypos);
			
		}
		
		override protected function initialize():void
		{
			super.initialize();
			
			enabled = false;
			
			_timer = new Timer(_delay);				
			_timer.addEventListener(TimerEvent.TIMER, timerHandler);
			
		}
		
		override protected function createChildren():void
		{
			super.createChildren();
			
			_textField = new TextField();
			_textField.wordWrap = true;			
			_textField.multiline = true;			
			_textField.selectable = false;
			
			addChild(_textField);
			
		}
		
		private function timerHandler(evt:TimerEvent):void
		{
			if (_timer.currentCount > _text.length)
			{
				stop();
			}
			else
			{				
				_textField.appendText(_text.charAt(_timer.currentCount - 1));
				_textField.scrollV = _textField.maxScrollV;
				_handle != null && _handle();
			}
			
			
		}
		
		public function completeNow():void
		{
			if (_timer.running)
			{				
				_textField.appendText(_text.substr(_timer.currentCount - 1));
				stop();					
			}
			
		}
		
		public function start():void
		{
			if (_timer.running || _text == null || _text.length == 0)
			{
				return;
			}
			
			_timer.reset();
			_timer.start();
		}
		
		public function stop():void
		{
			_timer.stop();
			_handle != null && _handle();
		}
		
		public function get text():String
		{
			return _text;
		}
		
		public function set text(value:String):void
		{
			_text = value;
			_textField.text = "";
		}
		
		public function get textField():TextField
		{
			return _textField;
		}
				
		public function dispose():void
		{
			_timer.start();			
			_timer.removeEventListener(TimerEvent.TIMER, timerHandler);
			
			_timer = null;
			_handle = null;
		}
		
	}
}